"""
简单的缓存管理器
提供基本的缓存功能，包括设置、获取、删除和清理缓存
"""

import json
import os
import hashlib
import time
from typing import Any, Dict, Optional
from pathlib import Path

class CacheManager:
    """简单的文件缓存管理器"""
    
    def __init__(self, cache_dir: str = "cache"):
        """
        初始化缓存管理器
        
        Args:
            cache_dir: 缓存文件存储目录
        """
        self.cache_dir = Path(cache_dir)
        self.cache_dir.mkdir(exist_ok=True)
        
    def _get_cache_key(self, key: str) -> str:
        """生成缓存文件名"""
        return hashlib.md5(key.encode()).hexdigest() + ".json"
        
    def _get_cache_path(self, key: str) -> Path:
        """获取缓存文件路径"""
        return self.cache_dir / self._get_cache_key(key)
        
    def set(self, key: str, value: Any, ttl: int = 3600) -> bool:
        """
        设置缓存
        
        Args:
            key: 缓存键
            value: 缓存值
            ttl: 生存时间（秒）
            
        Returns:
            bool: 是否设置成功
        """
        try:
            cache_data = {
                "value": value,
                "expires_at": time.time() + ttl,
                "created_at": time.time()
            }
            
            cache_path = self._get_cache_path(key)
            with open(cache_path, 'w', encoding='utf-8') as f:
                json.dump(cache_data, f, ensure_ascii=False, indent=2)
            return True
        except Exception as e:
            print(f"设置缓存失败: {e}")
            return False
            
    def get(self, key: str) -> Optional[Any]:
        """
        获取缓存
        
        Args:
            key: 缓存键
            
        Returns:
            缓存值，如果不存在或已过期则返回None
        """
        try:
            cache_path = self._get_cache_path(key)
            if not cache_path.exists():
                return None
                
            with open(cache_path, 'r', encoding='utf-8') as f:
                cache_data = json.load(f)
                
            # 检查是否过期
            if time.time() > cache_data.get("expires_at", 0):
                self.delete(key)
                return None
                
            return cache_data.get("value")
        except Exception as e:
            print(f"获取缓存失败: {e}")
            return None
            
    def delete(self, key: str) -> bool:
        """
        删除缓存
        
        Args:
            key: 缓存键
            
        Returns:
            bool: 是否删除成功
        """
        try:
            cache_path = self._get_cache_path(key)
            if cache_path.exists():
                cache_path.unlink()
            return True
        except Exception as e:
            print(f"删除缓存失败: {e}")
            return False
            
    def clear(self) -> bool:
        """
        清理所有缓存
        
        Returns:
            bool: 是否清理成功
        """
        try:
            for cache_file in self.cache_dir.glob("*.json"):
                cache_file.unlink()
            return True
        except Exception as e:
            print(f"清理缓存失败: {e}")
            return False
            
    def get_cache_info(self) -> Dict[str, Any]:
        """
        获取缓存信息
        
        Returns:
            缓存统计信息
        """
        try:
            cache_files = list(self.cache_dir.glob("*.json"))
            total_files = len(cache_files)
            
            # 统计有效缓存
            valid_cache = 0
            total_size = 0
            
            for cache_file in cache_files:
                try:
                    with open(cache_file, 'r', encoding='utf-8') as f:
                        cache_data = json.load(f)
                    
                    if time.time() <= cache_data.get("expires_at", 0):
                        valid_cache += 1
                        total_size += cache_file.stat().st_size
                except:
                    pass
                    
            return {
                "total_files": total_files,
                "valid_cache": valid_cache,
                "total_size_bytes": total_size,
                "cache_dir": str(self.cache_dir.absolute())
            }
        except Exception as e:
            print(f"获取缓存信息失败: {e}")
            return {
                "total_files": 0,
                "valid_cache": 0,
                "total_size_bytes": 0,
                "cache_dir": str(self.cache_dir.absolute()),
                "error": str(e)
            }

# 创建全局缓存管理器实例
cache_manager = CacheManager()
